package com.tsugun.mediaplayer.view.fragment.subfragment;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tsugun.mediaplayer.R;
import com.tsugun.mediaplayer.model.entity.MusicModel;
import com.tsugun.mediaplayer.model.entity.SheetModel;
import com.tsugun.mediaplayer.presenter.manager.MusicFragmentManager;
import com.tsugun.mediaplayer.presenter.provider.ListProvider;
import com.tsugun.mediaplayer.presenter.utils.ConverterHelper;
import com.tsugun.mediaplayer.view.activity.IndexActivity;
import com.tsugun.mediaplayer.view.adapter.MusicMenuAdapter;
import com.tsugun.mediaplayer.view.adapter.SheetItemAdapter;
import com.tsugun.mediaplayer.view.fragment.DownloadFragment;
import com.tsugun.mediaplayer.view.fragment.FavoriteFragment;
import com.tsugun.mediaplayer.view.fragment.FollowFragment;
import com.tsugun.mediaplayer.view.fragment.LatelyFragment;
import com.tsugun.mediaplayer.view.fragment.LocalFragment;
import com.tsugun.mediaplayer.view.fragment.SheetFragment;
import com.tsugun.mediaplayer.view.widget.MusicMenuDialog;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * create an instance of this fragment.
 */
public class MyFragment extends SubBaseFragment {

    private static final int MENU_ITEM_EDIT = 0;
    private static final int MENU_ITEM_SHEET_DELETE = 1;

    private static final String COUNT_AGES = "首";
    private static final String COUNT_TITLE_AGES = "/40";

    @BindView(R.id.id_my_local)
    RelativeLayout mRlLocal;
    @BindView(R.id.id_my_edit)
    ImageButton mIBtnMyEdit;
    @BindView(R.id.id_recycler_menu_my)
    RecyclerView mRvMySheet;
    @BindView(R.id.id_collection_edit)
    ImageButton mIBtnCollectionEdit;
    @BindView(R.id.id_recycler_menu_collection)
    RecyclerView mRvCollectionSheet;
    @BindView(R.id.id_music_count)
    TextView mTvCount;

    private View mFragment;
    private Context mContext;
    private Unbinder unbinder;
    private IndexActivity indexActivity;
    private ListProvider mProvider;
    private MusicFragmentManager mManager;

    // 歌单列表
    private List<SheetModel> mOriginalSheetList;
    private List<SheetModel> mCollectionSheetList;
    private SheetItemAdapter mOriginalAdapter;
    private SheetItemAdapter mCollectionAdapter;

    // 创建歌单会话框布局
    private AlertDialog mAlertDialog;
    private View mSheetCreateView;
    private EditText mEdtSheetCreate;
    private TextView mTxtTitleCount;

    // 歌单菜单
    private int mPosition;
    private MusicMenuDialog mDialog;
    private List<String> mOriginalMenuList;
    private List<String> mCollectionMenuList;
    private MusicMenuAdapter mOriginalMenuAdapter;
    private MusicMenuAdapter mCollectionMenuAdapter;
    private String mMenuTitle;

    // 编辑歌单会话框
    private AlertDialog mEditDialog;
    private View mSheetEditView;
    private EditText mEdtSheetEdit;
    private TextView mTxtTitleCountEdit;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mFragment = inflater.inflate(R.layout.fragment_my, container, false);
        mContext = container.getContext();
        unbinder = ButterKnife.bind(this, mFragment);

        initView();
        initData();
        bindData();
        return mFragment;
    }

    private void initView() {
        mPosition = 0;
        initSheetCreateDialog();
        initSheetEditDialog();
        initOriginalMenu();
        initCollectionMenu();
    }

    private void initData() {
        indexActivity = (IndexActivity) mContext;
        mManager = indexActivity.getMusicFragmentManager();
        mProvider = indexActivity.getListProvider();
        mOriginalSheetList = new ArrayList<>();
        mCollectionSheetList = new ArrayList<>();
    }

    private void bindData() {
        setCountText();
        showSheet();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    /**
     * 设置计数文本
     */
    private void setCountText() {
        String countText = mProvider.getMusicTotal() + COUNT_AGES;
        mTvCount.setText(countText);
    }

    /**
     * 显示歌单
     */
    private void showSheet() {
        if (mProvider == null) {
            return;
        }
        setSheetList();
        bindOriginalSheet();
        bindCollectionSheet();
    }

    /**
     * 更新歌单列表
     */
    public void updateList() {
        mOriginalAdapter.notifyDataSetChanged();
    }

    /**
     * 设置歌单列表
     */
    private void setSheetList() {
        mOriginalSheetList.clear();
        mCollectionSheetList.clear();
        for (SheetModel sheetModel : mProvider.getSheet()) {
            if (sheetModel.getOriginal()) {
                mOriginalSheetList.add(sheetModel);
            } else {
                mCollectionSheetList.add(sheetModel);
            }
        }
    }

    /**
     * 绑定原创歌单列表数据
     */
    private void bindOriginalSheet() {
        mOriginalAdapter = new SheetItemAdapter(mContext, mOriginalSheetList);
        mOriginalAdapter.setProvider(mProvider);
        mOriginalAdapter.setOnSheetItemClickListener(new SheetItemAdapter.OnSheetItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (((List<MusicModel>) mProvider.getMusicBySheet(mOriginalSheetList.get(position)))
                        .size() > 0) {
                    startSheetFragment(position);
                } else {
                    Snackbar.make(mRvMySheet, R.string.str_sheet_no_music, Snackbar.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onMenuClick(int position) {
                mPosition = position;
                showOriginalMenu();
            }
        });
        mRvMySheet.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        mRvMySheet.setAdapter(mOriginalAdapter);
//        mRvMySheet.addOnChildAttachStateChangeListener(getAttachListener());
    }

    private void startSheetFragment(int position) {
        Bundle bundle = new Bundle();
        bundle.putString(SheetFragment.INTENT_STRING_SHEET_TITLE, mOriginalSheetList
                .get(position).getTitle());
//                mManager.openFragment(MusicFragmentManager.FRAGMENT_TAG_SHEET, bundle);
        SheetFragment fragment = new SheetFragment();
        fragment.setArguments(bundle);
        mManager.openFragment(fragment);
    }

    /**
     * 绑定收藏歌单列表数据
     */
    private void bindCollectionSheet() {
        mCollectionAdapter = new SheetItemAdapter(mContext, mCollectionSheetList);
        mCollectionAdapter.setProvider(mProvider);
        mCollectionAdapter.setOnSheetItemClickListener(new SheetItemAdapter.OnSheetItemClickListener() {
            @Override
            public void onItemClick(int position) {

            }

            @Override
            public void onMenuClick(int position) {
                mPosition = position;
                showCollectionMenu();
            }
        });
        mRvCollectionSheet.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        mRvCollectionSheet.setAdapter(mCollectionAdapter);
    }

    /**
     * 初始化新建歌单会话框
     */
    private void initSheetCreateDialog() {
        mSheetCreateView = LayoutInflater.from(mContext).inflate(R.layout.layout_sheet_create, null);
        mEdtSheetCreate = (EditText) mSheetCreateView.findViewById(R.id.id_edt_title);
        mTxtTitleCount = (TextView) mSheetCreateView.findViewById(R.id.id_txt_title_count);
        // 监听文字输入，实时显示文字数
        mEdtSheetCreate.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String strCount = mEdtSheetCreate.getText().length() + COUNT_TITLE_AGES;
                mTxtTitleCount.setText(strCount);
            }
        });
    }

    /**
     * 初始化编辑歌单会话框
     */
    private void initSheetEditDialog() {
        mSheetEditView = LayoutInflater.from(mContext).inflate(R.layout.layout_sheet_edit, null);
        mEdtSheetEdit = (EditText) mSheetEditView.findViewById(R.id.id_edt_title);
        mTxtTitleCountEdit = (TextView) mSheetEditView.findViewById(R.id.id_txt_title_count);
        // 监听文字输入，实时显示文字数
        mEdtSheetEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String strCount = mEdtSheetEdit.getText().length() + COUNT_TITLE_AGES;
                mTxtTitleCountEdit.setText(strCount);
            }
        });
    }

    private SheetModel mEdtSheet; // 被编辑的sheet

    /**
     * 编辑歌单信息
     */
    private void editSheetInfo() {
        mEdtSheetEdit.setText(mEdtSheet.getTitle());
        if (mEditDialog != null) {
            mEditDialog.show();
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.DeleteAlertDialog);
        mEditDialog = builder.setView(mSheetEditView).setTitle(R.string.str_edit_title)
                .setNegativeButton(R.string.str_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton(R.string.str_submit, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        updateSheet(mEdtSheet);
                    }
                }).create();
        mEditDialog.show();
    }

    /**
     * 更新歌单
     */
    private void updateSheet(SheetModel sheetModel) {
        SheetModel newSheet = new SheetModel(sheetModel.getId(), mEdtSheetEdit.getText().toString(),
                sheetModel.getMusicIdList(), sheetModel.getImageUrl(), sheetModel.getCreateDate(),
                ConverterHelper.INSTANCE.getNowTime(), sheetModel.getAuthorId(), sheetModel.getOriginal());
        if (!mProvider.editSheet(sheetModel, newSheet)) {
            Toast.makeText(mContext, R.string.str_duplicate_name, Toast.LENGTH_SHORT).show();
            return;
        }
        setSheetList();
        mOriginalAdapter.notifyDataSetChanged();
        Toast.makeText(mContext, R.string.str_edit_complete, Toast.LENGTH_SHORT).show();
    }

    /**
     * 显示创建歌单会话框
     */
    private void showCreateSheetDialog() {
        if (mAlertDialog != null) {
            mEdtSheetCreate.setText("");
            mAlertDialog.show();
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.DeleteAlertDialog);
        mAlertDialog = builder.setView(mSheetCreateView).setTitle(R.string.str_create_title)
                .setNegativeButton(R.string.str_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton(R.string.str_submit, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        createSheet();
                    }
                }).create();
        mAlertDialog.show();
    }

    /**
     * 创建歌单
     */
    private void createSheet() {
        String createDate = ConverterHelper.INSTANCE.getNowTime();
        SheetModel sheetModel = new SheetModel(mEdtSheetCreate.getText().toString(),
                new ArrayList<String>(), createDate, createDate, null, true);
        sheetModel.setId(mProvider.setSheet(sheetModel));
        if (sheetModel.getId() == null) {
            // 重复名称导致的插入失败
            Toast.makeText(mContext, R.string.str_duplicate_name, Toast.LENGTH_SHORT).show();
            return;
        }
        mOriginalSheetList.add(sheetModel);
        mOriginalAdapter.notifyDataSetChanged();
        Toast.makeText(mContext, R.string.str_create_complete, Toast.LENGTH_SHORT).show();
    }

    @OnClick({R.id.id_my_favorite, R.id.id_my_follow, R.id.id_my_download, R.id.id_my_lately,
            R.id.id_my_local, R.id.id_my_edit, R.id.id_collection_edit})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.id_my_favorite:
                mManager.openFragment(new FavoriteFragment());
                break;
            case R.id.id_my_follow:
                mManager.openFragment(new FollowFragment());
                break;
            case R.id.id_my_download:
                mManager.openFragment(new DownloadFragment());
                break;
            case R.id.id_my_lately:
                mManager.openFragment(new LatelyFragment());
                break;
            case R.id.id_my_local:
                mManager.openFragment(new LocalFragment());
                break;
            case R.id.id_my_edit:
                showCreateSheetDialog();
                break;
            case R.id.id_collection_edit:
                break;
        }
    }

    /**
     * 初始化我的歌单菜单dialog数据
     */
    private void initOriginalMenu() {
        // 菜单项目标题
        mOriginalMenuList = new ArrayList<>();
        Collections.addAll(mOriginalMenuList, getResources().getStringArray(R.array.menu_item_title_list_sheet));
        // 图标
        int[] mIcons = new int[]{R.drawable.ic_menu_item_details, R.drawable.ic_menu_item_delete};
        mOriginalMenuAdapter = new MusicMenuAdapter(mContext, mOriginalMenuList, mIcons);
        mOriginalMenuAdapter.setOnMenuClickListener(new MusicMenuAdapter.OnMenuItemClickListener() {
            @Override
            public void onMenuClick(int pos) {
                // 菜单项点击事件
                switch (pos) {
                    case MENU_ITEM_EDIT:
                        mEdtSheet = mOriginalSheetList.get(mPosition);
                        editSheetInfo();
                        break;
                    case MENU_ITEM_SHEET_DELETE:
                        showDeleteSheetDialog(mOriginalSheetList, mOriginalAdapter);
                        break;
                }
                mDialog.dismiss();
            }
        });
    }

    /**
     * 初始化我的歌单菜单dialog数据
     */
    private void initCollectionMenu() {
        // 菜单项目标题
        mCollectionMenuList = new ArrayList<>();
        Collections.addAll(mCollectionMenuList, getResources().getStringArray(R.array.menu_item_title_list_sheet));
        // 图标
        int[] mIcons = new int[]{R.drawable.ic_menu_item_details, R.drawable.ic_menu_item_delete};
        mCollectionMenuAdapter = new MusicMenuAdapter(mContext, mCollectionMenuList, mIcons);
        mCollectionMenuAdapter.setOnMenuClickListener(new MusicMenuAdapter.OnMenuItemClickListener() {
            @Override
            public void onMenuClick(int pos) {
                // 菜单项点击事件
                switch (pos) {
                    case MENU_ITEM_EDIT:
                        break;
                    case MENU_ITEM_SHEET_DELETE:
                        showDeleteSheetDialog(mCollectionSheetList, mCollectionAdapter);
                        break;
                }
            }
        });
    }

    /**
     * 显示删除确认会话框
     */
    private void showDeleteSheetDialog(final List<SheetModel> list, final SheetItemAdapter adapter) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.DeleteAlertDialog);
        AlertDialog dialog = builder.setMessage(R.string.str_msg_delete_content_sheet)
                .setNegativeButton(R.string.str_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton(R.string.str_delete, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        removeSheet(list, adapter);
                    }
                }).create();
        dialog.show();
    }

    /**
     * 删除歌单
     */
    private void removeSheet(List<SheetModel> list, SheetItemAdapter adapter) {
        mProvider.removeSheet(list.get(mPosition));
        list.remove(mPosition);
        adapter.notifyDataSetChanged();
    }

    /**
     * 菜单会话框
     */
    private void showMenu(MusicMenuAdapter adapter) {
        MusicMenuDialog.Builder builder = new MusicMenuDialog.Builder(mContext, adapter, mMenuTitle);
        mDialog = builder.create();
        mDialog.show();
    }

    /**
     * 显示歌曲菜单
     */
    private void showOriginalMenu() {
        mMenuTitle = "歌单：" + mOriginalSheetList.get(mPosition).getTitle();
        showMenu(mOriginalMenuAdapter);
    }

    /**
     * 显示歌曲菜单
     */
    private void showCollectionMenu() {
        mMenuTitle = "歌单：" + mCollectionSheetList.get(mPosition).getTitle();
        showMenu(mCollectionMenuAdapter);
    }
}
